#-*- coding: utf-8 -*-
'''
Created on Jun 24, 2012

@author: bbg
'''


from helper.login_session_manager import LoginSessionManager
from helper.cdkey_manager import CdkeyManager 
import dbwrapper
from dbwrapper.companyx.user_right import UserRight
from dbwrapper.company_management.company import Company
from dbwrapper.company_management.rights import Rights 
from dbwrapper.companyx.user import User
from dbwrapper.companyx.shop import Shop
from dbwrapper.companyx.login_session import LoginSession
import json
from service_base import ServiceBase 
from common.debug import Debug
import cgi
import cStringIO
import uuid

class CdkeyService(ServiceBase):
    '''
        激活CDKEY
    '''

    def __init__(self, start_response):
        
        ServiceBase.__init__(self, start_response)
        self.debug = Debug()
    
    def application(self, params):
        '''
        0. 激活
        1 权限验证
        '''
        #params = parse(None, environ)           
        self.debug.d("CdkeyService")          
        login_type = params.getfirst('type')
        if login_type == '0': # client激活CDKEY
            return self._clientReActiveCDKEY(params)
        elif login_type == '1': # client通过cdkey验证是否有某项权限
            return self._clientRightyanzheng(params)
        
        return self._responseInvalidParam()
    

    def _checkValid(self, request_params):
        '''
                    检查各个参数是否合法
        '''
        try:
            self.debug.d("_checkValid")
            cdkey = request_params.getfirst('cdkey')
            uuid = request_params.getfirst('uuid')
            username=request_params.getfirst('username')
            pwd=request_params.getfirst('pwd')
            company_id=request_params.getfirst('company_id')
            shop_id=request_params.getfirst('shop_id')
        
            if cdkey == None or uuid == None or username==None or company_id==None or shop_id==None or pwd==None:
                return (-1, '参数不完整')
        
            #判断企业ID是否合法
            dbsession=self._returndbsession()      
            intcomp=LoginSessionManager.isValidCompanyid(company_id,dbsession)
            if intcomp == False:       
                return (-1,"企业不存在")
        
                
            #check cdkey mapping
            dbmap = CdkeyManager.getCompanyShopIdPair(cdkey, dbsession)
            self.debug.d("LoginService: map to campany_id,shop_id:%s" % repr(dbmap))
       
            if dbmap == None:
                return (103, "无效的cdkey")
        
            if int(dbmap[0])!=int(company_id) or  int(dbmap[1])!=int(shop_id):
                return (-2, "输入的企业ID和店铺ID无效")
         
        #判断当前的CDKEY的状态：已经激活或者已经过期 或者该UUID 不为空都返回
            state=dbmap[2]
            if state==1:
                return (103, "cdkey 已经激活，不可以重新激活")
        
            if state=="2":
                return (103, "cdkey 已经过期，不可以重新激活")
        
                   
            if CdkeyManager.checkhasCompanyUUID(uuid,dbsession) is True:
                return (103, "UUID已经绑定，不可以重复绑定")
            
            #判断帐号和密码是否正确
            LoginSession.doMapping(company_id)
            User.doMapping(company_id)                 
            users = dbsession.query(User).filter(User.name == username)
            if users.count() == 0:
                return (-1, '用户名不存在')
               
            if users.first().pwd != pwd:
                return (-2, '密码不正确')
            
            
            return (0,'ok')
        
        except Exception, e:
            self.debug.d("_checkValid:Exception:%s" % e)
            return (-2, '参数不正确')
         
         
         
        return  (0,'ok')
         
         
         
             
        
  

              
        


    def _clientReActiveCDKEY(self, request_params):
        '''
              负责客户端激活CDKEY 
        '''
        dbmap=self._checkValid(request_params)
        self.debug.d("dbmap:%s" % repr(dbmap))
        if dbmap[0]!=0:
           return self._responseError(dbmap[0], dbmap[1])
        
        cdkey = request_params.getfirst('cdkey')
        uuid = request_params.getfirst('uuid')
               
        dbsession=self._returndbsession()              
        dbmapb=CdkeyManager.bindUuidCDkey(cdkey, uuid, dbsession)
        
        if dbmapb is None:
            #response cdkey invalid, login failed
            self.debug.e('bindUuidCDkey:error %s' % cdkey)
            return self._responseError(103, "激活CDKEY失败")
                 
        response_params={}
        response_params["ret"]=0
        response_params["msg"]="success"
        response_params["company_id"]=dbmapb[0]
        response_params["shop_id"]=dbmapb[1]
        response_params["uuid"]=dbmapb[2]
        response_params["cdkey"]=dbmapb[3]
               
        strtemp=json.dumps(response_params)    
        
        return self._response(strtemp)
        
 

        


    def _clientRightyanzheng(self, request_params):
        '''
              负责客户端权限验证 
        '''

        uuid = request_params.getfirst('uuid')
        cdkey= request_params.getfirst('cdkey')
        username = request_params.getfirst('username')  
        userid=request_params.getfirst('userid')     
        right_name=request_params.getfirst('right_name')  
        token = request_params.getfirst('token')
 
        if uuid == None or cdkey == None or username==None or userid==None or right_name==None or token==None:
            return self._responseError(-1,"参数不完整")
        #获取
        dbsession=self._returndbsession()
        #匹配CDKEY 并返回企业ID和SHOPID hasbindUuidCDkey
        dbmap = CdkeyManager.hasbindUuidCDkey(cdkey,uuid,dbsession)
        if dbmap == None:
            return  self._responseError(-1,"CDKEY无法匹配")
        
        company_id=dbmap[0]    
        #检查TOKEN是否过期
        intcomp = LoginSessionManager.isValidSession(company_id, username, token, dbsession)        
        if intcomp==False:
            return self._responseError(107, 'TOKEN 已经过期')
            

        #最后判断权限是否拥有
        UserRight.doMapping(company_id)
        userRight = dbsession.query(UserRight).filter(UserRight.user_id ==userid ).filter(UserRight.right_name ==right_name )
    
        if userRight.count() == 0:
                return self._responseError(-1, '没有权限')
                    
        response_params={}
        response_params["ret"]=0
        response_params["msg"]="有权限"
                    
        strtemp=json.dumps(response_params)    
        
        return self._response(strtemp)
        
 
        
         
 

